﻿using MusicExplorer.Repository.Internals;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MusicExplorer.Common
{
    public sealed class Downloader : IDownloader
    {
        private static Downloader s_instance = new Downloader();

        public static Downloader Instance { get { return s_instance; } }

        public static Downloader New { get { return new Downloader(); } }

        private Downloader()
        {

        }

        private HttpClient m_client;
        private void InitializeClient()
        {
            var handler = new HttpClientHandler();
            handler.UseDefaultCredentials = false;
            handler.Proxy = WebRequest.DefaultWebProxy;
            handler.Proxy.Credentials = new NetworkCredential("massonal", "jes8mo@");
            m_client = new HttpClient(handler);
        }

        public async Task<string> GetOnlineSourceAsync(string url, System.Threading.CancellationToken token)
        {
            if (string.IsNullOrEmpty(url)) return string.Empty;

            if (m_client == null) InitializeClient();

            token.Register(() => m_client.CancelPendingRequests());

            using (var response = await m_client.GetAsync(url, token))
            {
                using (var cancel = token.Register(() => response.Dispose()))
                {
                    if (token.IsCancellationRequested) return string.Empty;

                    return await response.Content.ReadAsStringAsync();
                }
            }
        }

        public async Task<byte[]> GetOnlineDataAsync(string url, System.Threading.CancellationToken token)
        {
            if (string.IsNullOrEmpty(url)) return null;

            if (m_client == null) InitializeClient();

            token.Register(() => m_client.CancelPendingRequests());

            return await m_client.GetByteArrayAsync(url);
        }
    }
}
